package com.usian.service.lmpl;

import com.usian.articles.Articles;
import com.usian.column.Vermicelli;
import com.usian.mapper.MessageMapper;
import com.usian.message.Message;
import com.usian.service.MessageService;
import com.usian.user.User;
import com.usian.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class MessageServicelmpl  implements MessageService {
    @Autowired
    private MessageMapper messageMapper;

    @Override
    public List<Message> selectMessageList(Integer acceptId, Integer sendId) {
        List<Message> messagelist = messageMapper.selectMessageList(acceptId,sendId);
        ArrayList<Message> arrayList = new ArrayList<>();
        for (Message message : messagelist) {
            User user = messageMapper.selectUserOne(message.getSendId());
            message.setName(user.getName());
            message.setImage(user.getImage());
            arrayList.add(message);
        }
        return arrayList;
    }

    @Override
    public List<Message> find(Integer userid, Integer type) {
        // 查询自己接收到的数据
       List<Message> messagelist = messageMapper.find(userid);
       // 获取发送者id
        Set<Integer> sendIdSet = new HashSet<>();
        for (Message message : messagelist) {
            sendIdSet.add(message.getSendId());
        }
        ArrayList<Message> arrayList = new ArrayList<>();
        //根据发送者id查询发送者最后一条信息
        for (Integer sendId : sendIdSet) {
            Message messageList = messageMapper.findend(sendId);
            Message acceptId = messageMapper.findea(messageList.getSendId(),messageList.getAcceptId());
            User user = messageMapper.selectUserOne(messageList.getSendId());
            messageList.setName(user.getName());
            if (!messageList.getMessage().equals(acceptId.getMessage())){
                messageList.setMessage(acceptId.getMessage());
            }
            messageList.setImage(user.getImage());
            if (user.getIsDesigner()!=type){
                arrayList.add(messageList);
            }
        }
        return arrayList;
    }

    @Override
    public Result send(Message message1) {
        Integer i = messageMapper.insert(message1);
        if (i>0){
            return Result.success();
        }else {
            return Result.error("发送失败");
        }
    }
}
